/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DepViewPanel.java
 *
 * Created on 29/11/2011, 21:41:47
 */

package proj5labbd.graphics.dependente;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Paine referente a visualização  dos dependentes
 */
public class DepViewPanel extends OperationPanel {

    private ArrayList<String> fields;
    /** Creates new form DepViewPanel */
    public DepViewPanel(DepFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        fields = new ArrayList<String>();
        DepAction act = new DepAction();
        jbView.addActionListener(act);
        jchkNomeFunc.addItemListener(act);
        jchkNomeDep.addItemListener(act);
        jchkDataNasc.addItemListener(act);
        jchkSexo.addItemListener(act);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam = new javax.swing.JPanel();
        jlbFuncionario = new javax.swing.JLabel();
        jlbNomeDependente = new javax.swing.JLabel();
        jlbDataNasc = new javax.swing.JLabel();
        jlbSexo = new javax.swing.JLabel();
        jcbSexo = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbFuncionario = new javax.swing.JTable();
        jftxtDate = new javax.swing.JFormattedTextField();
        jtxtNome = new javax.swing.JTextField();
        jpnField = new javax.swing.JPanel();
        jchkNomeFunc = new javax.swing.JCheckBox();
        jchkNomeDep = new javax.swing.JCheckBox();
        jchkDataNasc = new javax.swing.JCheckBox();
        jchkSexo = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbView = new javax.swing.JTable();
        jbView = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Visualização"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros da busca"));

        jlbFuncionario.setText("Funcionário");

        jlbNomeDependente.setText("Nome do Dependente");

        jlbDataNasc.setText("Data de Nascimento");

        jlbSexo.setText("Sexo");

        jcbSexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "", "F", "M" }));

        jtbFuncionario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jtbFuncionario);

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtDate.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 518, Short.MAX_VALUE)
                    .addComponent(jlbFuncionario, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbNomeDependente)
                            .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jftxtDate)
                            .addComponent(jlbDataNasc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbSexo)
                            .addComponent(jcbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jlbNomeDependente)
                            .addComponent(jlbDataNasc))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jlbFuncionario))
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbSexo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );

        jpnField.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos a selecionar"));

        jchkNomeFunc.setText("Nome do Funcionário");

        jchkNomeDep.setText("Nome do Dependente");

        jchkDataNasc.setText("Data de Nascimento");

        jchkSexo.setText("Sexo");

        javax.swing.GroupLayout jpnFieldLayout = new javax.swing.GroupLayout(jpnField);
        jpnField.setLayout(jpnFieldLayout);
        jpnFieldLayout.setHorizontalGroup(
            jpnFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnFieldLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jchkNomeFunc)
                    .addComponent(jchkNomeDep)
                    .addComponent(jchkDataNasc)
                    .addComponent(jchkSexo))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpnFieldLayout.setVerticalGroup(
            jpnFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnFieldLayout.createSequentialGroup()
                .addComponent(jchkNomeFunc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jchkNomeDep)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jchkDataNasc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jchkSexo)
                .addContainerGap(170, Short.MAX_VALUE))
        );

        jtbView.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbView);

        jbView.setText("Visualizar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbView, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpnParam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpnField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 777, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jpnField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                .addComponent(jbView))
        );
    }// </editor-fold>//GEN-END:initComponents

    //ação tomada após o click do mouse no painel
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbFuncionario.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    //ação tomada pela apresentação do painel ao usuário
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações das tabelas.");
        }
    }//GEN-LAST:event_formComponentShown


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbView;
    private javax.swing.JComboBox jcbSexo;
    private javax.swing.JCheckBox jchkDataNasc;
    private javax.swing.JCheckBox jchkNomeDep;
    private javax.swing.JCheckBox jchkNomeFunc;
    private javax.swing.JCheckBox jchkSexo;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JLabel jlbDataNasc;
    private javax.swing.JLabel jlbFuncionario;
    private javax.swing.JLabel jlbNomeDependente;
    private javax.swing.JLabel jlbSexo;
    private javax.swing.JPanel jpnField;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtbFuncionario;
    private javax.swing.JTable jtbView;
    private javax.swing.JTextField jtxtNome;
    // End of variables declaration//GEN-END:variables

    //configuração da(s) tabela(s) utilizando informações resgatadas da base de dados
    public void setupTable() throws SQLException {
        String [] titlesDe = {"ID","Nome","Data de nascimento","CPF","Salario","Carreira"};
        String [] fieldsDe= {"funcionario.idFu","funcionario.nomeCompletoFu","funcionario.dataNascimentoFu",
            "funcionario.cpfFu","funcionario.salarioFu","tipoFuncionario.descricaoTipoFu"
        };
        String [] paramsDe = {"funcionario.idTipoFu=tipoFuncionario.idTipoFu"};
        String [][] result = dbInterface.view(fieldsDe,paramsDe,new String[]{"funcionario","tipoFuncionario"});
        
        DefaultTableModel model = new DefaultTableModel(result,titlesDe);
        jtbFuncionario.setModel(model);
        
    }
    
    //ouvinte de btões e de chkbox
    class DepAction implements ActionListener, ItemListener {
        //ação do botão de visualização
        public void actionPerformed(ActionEvent e) {
            
            String [] titles = {"ID do funcionário","Nome Completo do Dependente","Data de nascimento","Sexo"};
            String [] tables = {"dependente"};
            boolean join = false;
            
            try {
                ArrayList<String> param = new ArrayList<String>();
                String s[][];
                
                if (jtxtNome.getText().trim().compareTo("") != 0) {
                    param.add("UPPER(dependente.nomeCompletoDe)=UPPER('"+jtxtNome.getText()+"')");                
                }
                if (jftxtDate.getText().compareTo("  -  -    ") != 0) {
                    param.add("TO_DATE(dependente.dataNascimentoDe,'DD-MM-YYYY')=TO_DATE('"+ 
                            jftxtDate.getText()+"','DD-MM-YYYY')");
                }
                if (jcbSexo.getSelectedItem().toString().compareTo("") != 0) {
                    param.add("UPPER(dependente.sexoDe)=UPPER('"+jcbSexo.getSelectedItem().toString()+"')");
                }
                if (jtbFuncionario.getSelectedRowCount() == 1) {
                    param.add("dependente.idFu="+jtbFuncionario.getValueAt(jtbFuncionario.getSelectedRow(), 0));
                    param.add("funcionario.idFu=dependente.idFu"); 
                    tables = new String[]{"dependente","funcionario"}; 
                    join = true;
                }

                if (param.size() > 0 ) {
                    
                        String[] paramArray = new String[param.size()];
                        
                        if (fields.size() > 0) {
                            
                            if (!join) {
                                param.add("funcionario.idFu=dependente.idFu"); 
                                tables = new String[]{"dependente","funcionario"};                        
                            } 
                       
                            String[] fieldArray = new String[fields.size()];
                            param.toArray(paramArray);
                            fields.toArray(fieldArray);
                            s = dbInterface.view(fieldArray, paramArray, tables);
                            jtbView.setModel(
                                    new DefaultTableModel(s,fieldArray)
                                    );
                        }
                        else {
                            param.toArray(paramArray);
                            s = dbInterface.view(null, paramArray, tables);
                            jtbView.setModel(
                                    new DefaultTableModel(s,titles)
                                    );
                        }
                    
                     
                 }
                
                else {
                    if (fields.size() > 0) {
                            
                            if (!join) {
                                param.add("funcionario.idFu=dependente.idFu"); 
                                tables = new String[]{"dependente","funcionario"};                        
                            }
                            String[] fieldArray = new String[fields.size()];
                            fields.toArray(fieldArray);
                            s = dbInterface.view(fieldArray, null, tables);
                            jtbView.setModel(
                                    new DefaultTableModel(s,fieldArray)
                                    );
                        }
                    else { 
                        s = dbInterface.view(null, null, tables);
                        jtbView.setModel(
                                        new DefaultTableModel(s,titles)
                                        );
                    }
                }
            }
            catch (SQLException ex) {
                frame.printException(ex);
                JOptionPane.showMessageDialog(null, "Erro ao resgatar as tuplas desejadas.");
            } finally {
                join = false;
            }
            
        }
        //ação das checkbox quando possuem seuu estado modificado
         public void itemStateChanged(ItemEvent ie) {
            if ( ie.getStateChange() == ItemEvent.SELECTED ) {
                if (ie.getSource() == jchkNomeFunc) {
                    fields.add("funcionario.nomeCompletoFu");
                }
                if (ie.getSource() == jchkNomeDep) {
                    fields.add("dependente.nomeCompletoDe");
                }
                if (ie.getSource() == jchkDataNasc) {
                    fields.add("dependente.dataNascimentoDe");
                }
                if (ie.getSource() == jchkSexo) {
                    fields.add("dependente.sexoDe");
                }
            }
            if ( ie.getStateChange() == ItemEvent.DESELECTED ) {
                if (ie.getSource() == jchkNomeFunc) {
                    fields.remove("funcionario.nomeCompletoFu");
                }
                if (ie.getSource() == jchkNomeDep) {
                    fields.remove("dependente.nomeCompletoDe");
                }
                if (ie.getSource() == jchkDataNasc) {
                    fields.remove("dependente.dataNascimentoDe");
                }
                if (ie.getSource() == jchkSexo) {
                    fields.remove("dependente.sexoDe");
                }
            }
        }
        
    }
    
}
